package com.emm.yixun.mobile.ui.analysis;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.MainProjectAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.customview.BarCharts;
import com.emm.yixun.mobile.model.GetPaymentNotSignedList;
import com.emm.yixun.mobile.model.GetPaymentNotSignedList.PaymentModeList;
import com.emm.yixun.mobile.model.GetPriceRecordList;
import com.emm.yixun.mobile.model.GetProjectList;
import com.emm.yixun.mobile.model.GetProjectList.ProjectList;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 算价分析
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:12:59
 */
public class CalculatePriceAnalysisActivity extends SwipeBackActivity {
	private static final String TAG = "CalculatePriceAnalysisActivity";

	/** 标题 */
	TextView title_main;

	/** Back按钮 */
	ImageView back_btn;

	LinearLayout open_layout_analysis;

	TextView name_time_analysis;

	private BarChart spreadBarChart_1, spreadBarChart_2;
	private BarData mBarData;
	private BarCharts mBarCharts;

	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;

	@Override
	protected void onResume() {
		BaseActivity.activity = this;
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.calculateprice_analysis_activity);

		SetSwipeBackLayout(mSwipeBackLayout);

		BaseActivity.activity = this;

		initView();
		initBtn();
		getPriceRecordList("1");
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:48:06
	 */
	private void initView() {
		title_main = (TextView) findViewById(R.id.title_main);
		title_main.setText("算价分析");
		back_btn = (ImageView) findViewById(R.id.back_btn);
		open_layout_analysis = (LinearLayout) findViewById(R.id.open_layout_analysis);
		name_time_analysis = (TextView) findViewById(R.id.name_time_analysis);
		spreadBarChart_1 = (BarChart) findViewById(R.id.spreadBarChart_1);
		spreadBarChart_2 = (BarChart) findViewById(R.id.spreadBarChart_2);
		SetRelativiLayoutPadding(R.id.main_head_top_rela);
		mBarCharts = new BarCharts();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:48:17
	 */
	private void initBtn() {
		back_btn.setVisibility(View.VISIBLE);
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		open_layout_analysis.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SetsortPopu();
			}
		});
	}

	View viewproject;
	PopupWindow popuproject;
	/** 时间 */
	private int SelectPostion = 0;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 条件选择框
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:48:35
	 */
	@SuppressLint("WrongConstant")
	public void SetsortPopu() {
		viewproject = LayoutInflater.from(CalculatePriceAnalysisActivity.this).inflate(R.layout.mainproject_popu, null);
		popuproject = new PopupWindow(viewproject, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
				android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
		popuproject.setFocusable(true);
		popuproject.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
		popuproject.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popuproject.showAtLocation(open_layout_analysis, Gravity.TOP, 0, 0);
		popuproject.setFocusable(true);
		popuproject.setOutsideTouchable(true);
		viewproject.setFocusable(true);
		viewproject.setFocusableInTouchMode(true);
		viewproject.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					popuproject.dismiss();
					EmmApplication.setLog(CalculatePriceAnalysisActivity.this);
				}
				return false;
			}
		});

		viewproject.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popuproject.dismiss();
				EmmApplication.setLog(CalculatePriceAnalysisActivity.this);
			}
		});

		ListView popu_list = (ListView) viewproject.findViewById(R.id.popu_list);
		RelativeLayout top_relativelayout = (RelativeLayout) viewproject.findViewById(R.id.top_relativelayout);
		SetViewPaddingHeight(top_relativelayout, 100);
		ArrayList<ProjectList> ll = new ArrayList<ProjectList>();

		ProjectList m = new ProjectList();
		m.setProjectCode("1");
		m.setProjectName("今天");
		ll.add(m);

		ProjectList m2 = new ProjectList();
		m2.setProjectCode("2");
		m2.setProjectName("昨天");
		ll.add(m2);

		ProjectList m3 = new ProjectList();
		m3.setProjectCode("3");
		m3.setProjectName("本周");
		ll.add(m3);

		ProjectList m4 = new ProjectList();
		m4.setProjectCode("4");
		m4.setProjectName("上周");
		ll.add(m4);

		ProjectList m5 = new ProjectList();
		m5.setProjectCode("5");
		m5.setProjectName("本月");
		ll.add(m5);

		ProjectList m6 = new ProjectList();
		m6.setProjectCode("6");
		m6.setProjectName("上月");
		ll.add(m6);

		ProjectList m7 = new ProjectList();
		m7.setProjectCode("7");
		m7.setProjectName("近三月");
		ll.add(m7);

		ProjectList m8 = new ProjectList();
		m8.setProjectCode("8");
		m8.setProjectName("今年");
		ll.add(m8);

		final GetProjectList list = new GetProjectList();
		list.setProjectList(ll);

		MainProjectAdapter adapter = new MainProjectAdapter(CalculatePriceAnalysisActivity.this, list);
		popu_list.setAdapter(adapter);
		adapter.SetType(1);
		if (list.getProjectList().size() >= (SelectPostion + 1)) {
			adapter.SeleCt(SelectPostion);
			name_time_analysis.setText(list.getProjectList().get(SelectPostion).getProjectName());
		} else {
			adapter.SeleCt(0);
			name_time_analysis.setText(list.getProjectList().get(0).getProjectName());
		}
		popu_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				popuproject.dismiss();
				SelectPostion = position;
				EmmApplication.setLog(CalculatePriceAnalysisActivity.this);
				name_time_analysis.setText(list.getProjectList().get(position).getProjectName());
				int numbertype = SelectPostion + 1;
				Log.v(TAG, "numbertype:==>" + numbertype);
				// 调用接口
				getPriceRecordList(list.getProjectList().get(position).getProjectCode());
			}
		});
	}

	/**
	 * 查询算价分析
	 */
	GetPriceRecordList getpricerecord;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 查询算价分析
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param workloadTimeType
	 * @author tangxin
	 * @date 2016年12月7日 上午11:48:58
	 */
	private void getPriceRecordList(String workloadTimeType) {
		EmmApplication.updateUrl("getPriceRecordList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("workloadTimeType", workloadTimeType);
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getPriceRecordList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.showDialogForLoading(CalculatePriceAnalysisActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v(TAG, content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getpricerecord = JSONObject.parseObject(resData.toString(), GetPriceRecordList.class);

				if ("1".equals(getpricerecord.getResult())) {
					Log.v("获取成功", "");
					GetPaymentNotSignedList getpayment = new GetPaymentNotSignedList();
					ArrayList<PaymentModeList> paymentModeList = new ArrayList<GetPaymentNotSignedList.PaymentModeList>();
					if (null != getpricerecord.getHouseTypeList() && getpricerecord.getHouseTypeList().size() > 0) {
						for (int i = 0; i < getpricerecord.getHouseTypeList().size(); i++) {
							PaymentModeList p = new PaymentModeList();
							p.setPaymentModeAmount(getpricerecord.getHouseTypeList().get(i).getHouseTypeNum());
							p.setPaymentModeName(getpricerecord.getHouseTypeList().get(i).getHouseTypeName());
							paymentModeList.add(p);
						}
					} else {
						PaymentModeList p = new PaymentModeList();
						p.setPaymentModeAmount("0");
						p.setPaymentModeName(" ");
						paymentModeList.add(p);
					}
					getpayment.setPaymentModeList(paymentModeList);
					mBarData = mBarCharts.getBarData(paymentModeList.size(), getpayment, "算价次数");
					mBarCharts.showBarChart(spreadBarChart_1, mBarData, "算价次数统计");

					GetPaymentNotSignedList getpayment2 = new GetPaymentNotSignedList();
					ArrayList<PaymentModeList> paymentModeList2 = new ArrayList<GetPaymentNotSignedList.PaymentModeList>();
					if (null != getpricerecord.getPropertyTypeList() && getpricerecord.getPropertyTypeList().size() > 0) {
						for (int i = 0; i < getpricerecord.getPropertyTypeList().size(); i++) {
							PaymentModeList p = new PaymentModeList();
							p.setPaymentModeAmount(getpricerecord.getPropertyTypeList().get(i).getPropertyTypeNum());
							p.setPaymentModeName(getpricerecord.getPropertyTypeList().get(i).getPropertyTypeName());
							paymentModeList2.add(p);
						}
					} else {
						EmmApplication.T("当前没有统计数据");
						PaymentModeList p = new PaymentModeList();
						p.setPaymentModeAmount("0");
						p.setPaymentModeName(" ");
						paymentModeList2.add(p);
					}
					getpayment2.setPaymentModeList(paymentModeList2);
					mBarData = mBarCharts.getBarData(paymentModeList2.size(), getpayment2, "算价次数");
					mBarCharts.showBarChart(spreadBarChart_2, mBarData, "算价次数统计");

				} else {
					EmmApplication.T(getpricerecord.getErrorMsg().toString());
					Log.v("获取失败", "errorCode:" + getpricerecord.getErrorCode().toString() + "errorMsg:"
							+ getpricerecord.getErrorMsg().toString());
				}
			}
		});
	}

}
